package io.wins.vertx.web;

import io.vertx.core.Vertx;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.jwt.JWTAuth;
import io.vertx.ext.auth.jwt.JWTOptions;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;

public class TokenResource implements Resource {

    private Vertx vertx;
    private JWTAuth authProvider;
    private ServerProperties serverProperties;

    public static TokenResource create(final Vertx vertx, final ServerProperties serverProperties) {
        final TokenResource tokenResource = new TokenResource();
        tokenResource.vertx = vertx;
        tokenResource.serverProperties = serverProperties;
        tokenResource.authProvider = JWTAuth.create(vertx, serverProperties.getJwtAuthConfig());
        return tokenResource;
    }

    @Override
    public Resource init(final Router router) {
        router.get("/api/token")
                .produces("application/json")
                .handler(this::getToken);
        return this;
    }

    private void getToken(final RoutingContext routingContext) {
        final String token = this.authProvider
                .generateToken(new JsonObject(), new JWTOptions());
        //add token in session
        routingContext.session()
                .put("token", "Bearer " + token);
        routingContext.response()
                .setStatusCode(200)
                .putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaders.TEXT_HTML)
                .end(token);
    }
}
